package com.yc.hwc.web.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import com.yc.hwc.bean.User;

@WebListener
public class OnLineListener implements ServletContextListener,HttpSessionAttributeListener {

	private static Map<Long, User> loginedUsers = new HashMap<>();

	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {
		if ("loginedUser".equals(se.getName())) {
			User user = (User) se.getValue();
			loginedUsers.put(user.getId(), user);
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
		if ("loginedUser".equals(se.getName())) {
			User user = (User) se.getValue();
			loginedUsers.remove(user.getId());
		}
	}

	
	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
		if ("loginedUser".equals(se.getName())) {
			User user = (User) se.getValue();
			loginedUsers.put(user.getId(), user);
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		sce.getServletContext().setAttribute("loginedUsers", loginedUsers);
	}
	
	

}
